package com.zg.system.auth;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zg.common.core.R;
import com.zg.common.web.Req;
import com.zg.common.core.User;
import com.zg.common.core.dao.auth.AuthUser;
import com.zg.common.core.dao.auth.AuthUserDao;
import com.zg.common.core.util.PwdUtil;
import com.zg.system.auth.vo.ChangePwdVo;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Zxb
 */
@RestController
@RequiredArgsConstructor
public class PasswordController {

    private final AuthUserDao userDao;

    @PostMapping("/user/pwd/change")
    public R changePwd(@RequestBody ChangePwdVo param) {
        String oldPwd = param.getOldPwd();
        String newPwd = param.getNewPwd();
        if (StrUtil.isBlank(oldPwd)
                || StrUtil.isBlank(newPwd)) {
            return R.error("请输入新旧密码");
        }
        User u = Req.getCurrUser();
        AuthUser user = userDao.getById(u.getId());
        if (!user.getPassword().equals(oldPwd)) {
            return R.error("旧密码错误");
        }

        user.setPassword(newPwd);
        userDao.updateById(user);
        return R.success();
    }

    @PostMapping("/user/pwd/reset")
    public R<?> resetPwd(String username) {
        AuthUser u = userDao.getOne(
                new LambdaQueryWrapper<AuthUser>()
                        .eq(AuthUser::getUsername, username)
        );
        if (u == null) {
            return R.error("未找到用户");
        }
        u.setPassword(PwdUtil.generateDefaultPwd());
        userDao.updateById(u);
        return R.success();
    }

}
